import Taro from "@tarojs/taro";
import { trackError } from "./tracking";

// 初始化错误监控
export const initErrorMonitor = () => {
  // 监听全局错误
  Taro.onError((error) => {
    trackError({
      type: "global_error",
      ...error,
    });
  });

  // 监听未处理的Promise拒绝
  Taro.onUnhandledRejection((res) => {
    trackError({
      type: "unhandled_rejection",
      reason: res.reason,
      promise: res.promise,
    });
  });

  // 监听页面不存在
  Taro.onPageNotFound((res) => {
    trackError({
      type: "page_not_found",
      path: res.path,
      query: res.query,
      isEntryPage: res.isEntryPage,
    });
  });
};

// 自定义错误处理
export const handleError = (error, type = "custom_error") => {
  trackError({
    type,
    ...error,
  });
};

// 网络错误处理
export const handleNetworkError = (error) => {
  trackError({
    type: "network_error",
    url: error.url,
    method: error.method,
    status: error.status,
    message: error.message,
  });
};

// 表单验证错误处理
export const handleValidationError = (error) => {
  trackError({
    type: "validation_error",
    field: error.field,
    message: error.message,
    value: error.value,
  });
};
